<?php

class base {
	/**
	 * @var database 
	 */
	var $db = '';
	/**
	 * 构造函数
	 */
	
	static $intance = array();
	public function __construct()	{
		global  $abdb;
		$this->db = $abdb;
//		$this->db = DB::getInstance('main');
//		$this->db->query("SET NAMES '".DB_CHARSET."'");
	}
	
	public static function factory($class){
		if(!key_exists($class, self::$intance)){
			$file = PM_ROOT.'class/model/'.$class.'.class.php';
			if(file_exists($file)) 
				require $file;
				self::$intance[$class] = new $class();
		}
		return self::$intance[$class];
	}
	
}

class AB_Error {
	var $errors = array();
	var $error_data = array();

	function AB_Error($code = '', $message = '', $data = '') {
		if ( empty($code) )
			return;

		$this->errors[$code][] = $message;

		if ( ! empty($data) )
			$this->error_data[$code] = $data;
	}

	function get_error_codes() {
		if ( empty($this->errors) )
			return array();

		return array_keys($this->errors);
	}

	function get_error_code() {
		$codes = $this->get_error_codes();

		if ( empty($codes) )
			return '';

		return $codes[0];
	}

	function get_error_messages($code = '') {
		// Return all messages if no code specified.
		if ( empty($code) ) {
			$all_messages = array();
			foreach ( $this->errors as $code => $messages )
				$all_messages = array_merge($all_messages, $messages);

			return $all_messages;
		}

		if ( isset($this->errors[$code]) )
			return $this->errors[$code];
		else
			return array();
	}

	function get_error_message($code = '') {
		if ( empty($code) )
			$code = $this->get_error_code();
		$messages = $this->get_error_messages($code);
		if ( empty($messages) )
			return '';
		return $messages[0];
	}

	function get_error_data($code = '') {
		if ( empty($code) )
			$code = $this->get_error_code();

		if ( isset($this->error_data[$code]) )
			return $this->error_data[$code];
		return null;
	}

	function add($code, $message, $data = '') {
		$this->errors[$code][] = $message;
		if ( ! empty($data) )
			$this->error_data[$code] = $data;
	}

	function add_data($data, $code = '') {
		if ( empty($code) )
			$code = $this->get_error_code();

		$this->error_data[$code] = $data;
	}
}
